import { VEEdge, VELoop, VEMesh, VEVertex } from "../core/";

export function addLoop(
  struct: VEMesh,
  v1: VEVertex,
  v2: VEVertex,
  e1: VEEdge,
  allowParallels = false) {

  if (v1 === v2) {
    // TODO：网格结构异常，可能是类似一条细线一样的网格
    console.error('Vertices v1 and v2 should be different');
    throw new Error('Vertices v1 and v2 should be different');
  }

  // TODO：重复性检查
  if (!allowParallels) {
    // Check if v1 and v2 are already connected
    const currentLoop = v1.getLoopToVertex(v2);
    if (currentLoop) {
      return currentLoop;
    }
  }

  if (!v1.isFree() || !v2.isFree()) {
    console.error('Vertices v1 and v2 are not free');
    throw new Error('Vertices v1 and v2 are not free');
  }

  // Create new loops, by default twin loops are connected together
  // as prev/next in case vertices are isolated
  const loop1 = new VELoop(v1);
  const loop2 = new VELoop(v2);
  loop1.edge = e1;
  loop2.edge = e1;
  e1.loop = loop1;
  loop1.pair = loop2;
  loop1.next = loop2;
  loop1.prev = loop2;
  loop2.pair = loop1;
  loop2.next = loop1;
  loop2.prev = loop1;

  /*
   *        ↖       ↙
   *   out2   ↖   ↙   in2
   *            v2           
   *            ⇅        
   *            ⇅   
   *     loop1  ⇅  loop2     
   *            ⇅  
   *            ⇅  
   *            v1
   *    in1  ↗     ↘  out1
   *       ↗         ↘
   *            
   */


  // Update refs around v1 if not isolated
  const in1 = v1.freeLoopsInLoop().next().value;
  if (in1) {
    const out1 = in1.next;
    loop1.prev = in1;
    in1.next = loop1;

    loop2.next = out1;
    out1.prev = loop2;
  } else {
    v1.loop = loop1;
  }

  // // Update refs around v2 if not isolated
  const in2 = v2.freeLoopsInLoop().next().value;
  if (in2) {

    const out2 = in2.next;
    loop2.prev = in2;
    in2.next = loop2;

    loop1.next = out2;
    out2.prev = loop1;
  } else {
    v2.loop = loop2;
  }

  struct.loops.push(loop1);
  struct.loops.push(loop2);

  return loop1;
}
